//
//  UserAccount.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/6/28.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit

class UserAccount: NSObject  , NSCoding{
    var access_token : String
    var expires_in : NSTimeInterval
    var uid : String
    
    // 过期日期
    var expiresDate: NSDate
    
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    // 不写int 就需要在上面写初始值
    init(dict : [String : AnyObject]){
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        // 过期日期计算
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    // 跟据用户Uid  和 OAuth 授权  获取用户信息
    func loadUserInfo(finished: (account: UserAccount?, error: NSError?) -> () ) {
        let params = ["access_token" : access_token , "uid" : uid]
        
        NetWorkTools.sharedNetWorkTools().GET("2/users/show.json", parameters: params, success: { (_, JSON) -> Void in
            Debug.Log(JSON)
            let dict = JSON as! [String: AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
            
            // 设置全局用户信息
            sharedUserAccount = self
            
            finished(account : self , error : nil )
            }) { (account, error) -> Void in
                finished(account : nil , error : error)
        }
    }
    
    // MARK: - 保存和加载文件
    /// 归档路径，swift中的类常量都是使用 static 来定义的
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    // 加个? 表示返回可为空
    class func loadAccount() -> UserAccount? {
        Debug.Log(accountPath)
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount {
            
            // 判断日期是否过期，根当前系统时间进行`比较`，低于当前系统时间，就认为过期
            // 过期日期`大于`当前日期，结果应该是降序
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
       return nil
    }
    
    // MARK : 解档 归档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") 
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
}
